<script setup lang="ts">
import { addEnterpriseAPI, uploadAPI } from '@/apis/common';
import { getEnterpriseDetailAPI, getIndustryAPI, updateEnterpriseAPI } from '@/apis/enterprise';
import type { EnterpriseParams } from '@/types/common';
import type { Industry } from '@/types/enterprise';
import { CircleCheck } from '@element-plus/icons-vue';
import {  ElMessage, type FormRules, type UploadRawFile, type UploadRequestOptions, type UploadUserFile, type FormInstance } from 'element-plus';
import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const router = useRouter();

// 根据接口文档定义字段，用于表单双向绑定
const addForm = ref<EnterpriseParams>({
  name: '', // 企业名称
  legalPerson: '', // 法人
  registeredAddress: '', // 注册地址
  industryCode: 0, // 所在行业
  contact: '', // 企业联系人
  contactNumber: '', // 联系人电话
  businessLicenseUrl: '', // 营业执照url
  businessLicenseId: 0 // 营业执照id
}) 
// 所在行业列表
const industryList = ref<Industry[]>([])
// 调用接口获取行业列表
const getIndustry = async() => {
 const res=  await getIndustryAPI()
//  console.log(res);
 
 industryList.value=res.data
}
getIndustry()

// 添加企业表单校验
  const  addRules=ref<FormRules<EnterpriseParams>>({
    name: [
    { required: true, message: '企业名称为必填', trigger: 'blur' }
  ],
  legalPerson: [
    { required: true, message: '法人为必填', trigger: 'blur' }
  ],
  registeredAddress: [
    { required: true, message: '注册地址为必填', trigger: 'blur' }
  ],
  industryCode: [
    { required: true, message: '所在行业为必填', trigger: 'change' }
  ],
  contact: [
    { required: true, message: '企业联系人为必填', trigger: 'blur' }
  ],
  contactNumber: [
    { required: true, message: '企业联系人电话为必填', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: 'blur' },
  ],
  businessLicenseId: [
    { required: true, message: '请上传营业执照', trigger: 'blur' }
  ]
  })
// 表单整体校验
const formRef = ref<FormInstance>()

const onSubmit = async () => {
  try {
    // 等待验证完成
    await formRef.value?.validate()
  //  编辑企业获取后端所需数据
   const data=addForm.value
   if(route.params.id){
    // 编辑企业获取后端所需数据   这句AI生成的居然这么简洁，虽然我也不明白什么意思
    data.id=Number(route.params.id)
    await updateEnterpriseAPI(data)
    ElMessage.success('编辑成功')
   }else{
    await addEnterpriseAPI(addForm.value)
    ElMessage.success('添加成功')
   }
  
    router.back()
  } catch {
    ElMessage.error('表单验证失败')
  }
}

// 添加企业
const addEnterprise = () => {
   
}
addEnterprise()
// 保存营业执照数据
const fileList=ref<UploadUserFile[]>([])
// 上传营业执照
const onHttpRequest=async(options: UploadRequestOptions)=>{
  console.log(options);
 const  fd=new FormData()
 fd.append('file',options.file)
 fd.append('type','businessLicense2')
//  调用接口上传
   const res=   await uploadAPI(fd)
      //  console.log(res);
      //  将营业执照url赋值给addForm.businessLicenseUrl
      addForm.value.businessLicenseUrl=res.data.url
      addForm.value.businessLicenseId=res.data.id
       
  //  返回url
   return  res.data.url  
}
// 上传大小限制
const onBenforeUpload=async(rawFile: UploadRawFile)=>{
  if( rawFile.size>5*1024*1024){
ElMessage.error('上传营业执照图片大小不能超过 5MB!')
return false

  }
  if(rawFile.type!=='image/jpeg'&&rawFile.type!=='image/png'){
  ElMessage.error('上传营业执照图片格式不正确!')
  return false
}
}
// 删除营业执照
const onRemove=()=>{
  addForm.value.businessLicenseUrl=''
  addForm.value.businessLicenseId=0
  
  // 营业执照单独校验
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
}


// 获取企业详情
const getEnterpriseDetail = async (id: string) => {
  const res = await getEnterpriseDetailAPI(Number(id))
  // 回显数据
  const {contact,contactNumber,businessLicenseUrl,businessLicenseId,legalPerson,registeredAddress,industryCode,name}=res.data
  addForm.value.contact=contact
  addForm.value.contactNumber=contactNumber
  addForm.value.businessLicenseUrl=businessLicenseUrl
  addForm.value.businessLicenseId=businessLicenseId
  addForm.value.legalPerson=legalPerson
  addForm.value.registeredAddress=registeredAddress
  addForm.value.industryCode=industryCode
  addForm.value.name=name
}



const route=useRoute()
if(route.params.id){
  getEnterpriseDetail(route.params.id as string)

}


</script>

<template>
  <div class="add-enterprise">
    <header class="add-header">
      <el-page-header :content="$route.params.id?'编辑企业':'添加企业'" @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form label-width="100px" 
           :model="addForm" 
           :rules="addRules"
           ref="formRef">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name"  />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode">
                <el-option v-for="item in industryList" :key="item.industryCode"
                 :value="item.industryCode"
                 :label="item.industryName"  >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseId">
          <el-upload
            name="file"
            multiple
            :limit="1"
            :http-request="onHttpRequest"
            list-type="picture"
            v-model:file-list="fileList"  
            :before-upload="onBenforeUpload"
            accept=".png, .jpg, .jpeg"
           @remove="onRemove"

            >
          >
            <template #trigger>
               <el-button v-if="fileList.length<1" size="small" type="primary">点击上传</el-button>
               <el-button v-else type="success" :icon="CircleCheck" disabled>已上传</el-button>
            </template>
            <template #tip>
               <div class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </template>
          </el-upload>
              
            </el-form-item>

          </el-form>
        </div>
      </div>
    </main>
    {{ addForm }}
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="resetForm">重置</el-button>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </div>
    </footer>
  </div>
   
</template>

<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>